package com.koko.service.impl;

import com.github.pagehelper.Page;
import com.koko.constant.FileNameConstant;
import com.koko.game.entity.GameView;
import com.koko.game.vo.GameViewListVO;
import com.koko.game.vo.GameViewVO;
import com.koko.mapper.GameViewMapper;
import com.koko.properties.HttpParamsProperties;
import com.koko.properties.HttpPathProperties;
import com.koko.service.GameViewService;
import com.koko.utils.HttpUrlUtil;
import com.koko.utils.IOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
public class GameViewServiceImpl implements GameViewService {
    @Value("${koko.path.game}")
    private String basePath;

    @Value("${koko.urlPrefix}")
    private String baseUrl;

    @Autowired
    private GameViewMapper gameViewMapper;

    @Override
    @Transactional
    public void save(Long id, MultipartFile[] images, MultipartFile[] videos) {
        // 操作图片
        int imageCount = 1;// 计数器
        for (MultipartFile image : images) {
            String contentType = image.getContentType();
            // 判断必须为图片
            if (contentType.equals("image")) {
                // 1. 存入目标文件夹
                String imageFileName = IOUtil.saveFile(
                        image,
                        basePath + id + "/",
                        FileNameConstant.GAME_IMAGE + imageCount + IOUtil.getFileSuffix(image));
                // 2. 封装对象
                GameView gameView = GameView.builder()
                        .gameId(id)
                        .imageUrl(imageFileName)
                        .build();
                // 3. 存入数据库
                gameViewMapper.insert(gameView);
                imageCount++;
            }
        }
        // 操作视频
        if (videos != null && videos.length != 0) {
            int videoCount = 1; //计数器
            for (MultipartFile video : videos) {
                String contentType = video.getContentType();
                // 判断必须为图片
                if (contentType.equals("video")) {
                    // 1. 存入目标文件夹
                    String videoFileName = IOUtil.saveFile(
                            video,
                            basePath + id + "/",
                            FileNameConstant.GAME_VIDEO + videoCount + IOUtil.getFileSuffix(video));
                    // 2. 封装对象
                    GameView gameView = GameView.builder()
                            .gameId(id)
                            .videoUrl(videoFileName)
                            .build();
                    // 3. 存入数据库
                    gameViewMapper.insert(gameView);
                    videoCount++;
                }
            }
        }
    }

    @Override
    public void deleteByGameId(Long gameId) {
        gameViewMapper.deleteByGameId(gameId);
    }

    @Override
    public GameViewListVO getGameViewByGameId(Long gameId) {
        Page<GameView> gameViewPage = gameViewMapper.getGameViewPageByGameId(gameId);
        GameViewListVO gameViewListVO = new GameViewListVO(new ArrayList<String>(), new ArrayList<String>());
        for (GameView gameView : gameViewPage.getResult()) {
            if (gameView.getImageUrl() != null && !gameView.getImageUrl().isEmpty()) {
                String imageUrl = HttpUrlUtil.imageRequestUrlEncapsulate(
                        baseUrl + HttpPathProperties.GAME_VIEW_IMAGE_DOWNLOAD,
                        HttpParamsProperties.GAME_VIEW_ID + gameId,
                        HttpParamsProperties.GAME_VIEW_NAME + gameView.getImageUrl());
                gameViewListVO.getImageUrl().add(imageUrl);
            }
            if (gameView.getVideoUrl() != null && !gameView.getVideoUrl().isEmpty()) {
                String videoUrl = HttpUrlUtil.imageRequestUrlEncapsulate(
                        baseUrl + HttpPathProperties.GAME_VIEW_VIDEO_DOWNLOAD,
                        HttpParamsProperties.GAME_VIEW_ID + gameId,
                        HttpParamsProperties.GAME_VIEW_NAME + gameView.getVideoUrl());
                gameViewListVO.getVideoUrl().add(videoUrl);
            }
        }
        return gameViewListVO;
    }

    @Override
    public GameViewListVO getGameViewWithIdByGameId(Long gameId) {
        Page<GameView> gameViewPage = gameViewMapper.getGameViewPageByGameId(gameId);
        GameViewListVO gameViewListVO = new GameViewListVO(new ArrayList<GameViewVO>(), new ArrayList<GameViewVO>());
        for (GameView gameView : gameViewPage.getResult()) {
            if (gameView.getImageUrl() != null && !gameView.getImageUrl().isEmpty()) {
                GameViewVO gameViewVO = new GameViewVO();
                String imageUrl = HttpUrlUtil.imageRequestUrlEncapsulate(
                        baseUrl + HttpPathProperties.GAME_VIEW_IMAGE_DOWNLOAD,
                        HttpParamsProperties.GAME_VIEW_ID + gameId,
                        HttpParamsProperties.GAME_VIEW_NAME + gameView.getImageUrl());
                gameViewVO.setGameId(gameId);
                gameViewVO.setUrl(imageUrl);
                gameViewVO.setId(gameView.getId());
                gameViewListVO.getImageUrl().add(gameViewVO);
            }
            if (gameView.getVideoUrl() != null && !gameView.getVideoUrl().isEmpty()) {
                GameViewVO gameViewVO = new GameViewVO();
                String videoUrl = HttpUrlUtil.imageRequestUrlEncapsulate(
                        baseUrl + HttpPathProperties.GAME_VIEW_VIDEO_DOWNLOAD,
                        HttpParamsProperties.GAME_VIEW_ID + gameId,
                        HttpParamsProperties.GAME_VIEW_NAME + gameView.getVideoUrl());
                gameViewVO.setGameId(gameId);
                gameViewVO.setUrl(videoUrl);
                gameViewVO.setId(gameView.getId());
                gameViewListVO.getVideoUrl().add(gameViewVO);
            }
        }
        return gameViewListVO;
    }

    @Override
    public List<String> getGameImageViewOnCarouselByGameId(Long gameId) {
        List<GameView> gameViewList = gameViewMapper.getGameImageViewLimitInFourByGameId(gameId);
        List<String> list = new ArrayList<>();
        for (GameView gameView : gameViewList) {
            if (gameView.getImageUrl() != null && !gameView.getImageUrl().isEmpty()) {
                String imageUrl = HttpUrlUtil.imageRequestUrlEncapsulate(
                        baseUrl + HttpPathProperties.GAME_VIEW_IMAGE_DOWNLOAD,
                        HttpParamsProperties.GAME_VIEW_ID + gameId,
                        HttpParamsProperties.GAME_VIEW_NAME + gameView.getImageUrl());
                list.add(imageUrl);
            }
        }
        return list;
    }

    @Override
    @Transactional
    public void uploadVideo(Long gameId, MultipartFile chunk, Integer index, Integer totalChunks, String fileName) {
        String targetLocation = basePath + gameId + "/" + FileNameConstant.GAME_FOLDER_NAME;

        IOUtil.saveTempChunkFile(chunk, targetLocation, index, fileName);

        // 如果是最后一个分块，则合并文件
        if (index == totalChunks - 1) {
            IOUtil.mergeFile(targetLocation, fileName, totalChunks);
            // 插入数据库
            GameView gameView = new GameView();
            gameView.setGameId(gameId);
            gameView.setVideoUrl(fileName);
            gameViewMapper.insert(gameView);
        }
    }

    @Override
    @Transactional
    public void uploadImage(Long gameId, MultipartFile imageFile) {
        String targetLocation = basePath + gameId + "/" + FileNameConstant.GAME_FOLDER_NAME;
        // 1. 写入文件夹
        String fileName = IOUtil.saveFile(imageFile, targetLocation + "/");
        // 2. 插入数据库
        GameView gameView = new GameView();
        gameView.setGameId(gameId);
        gameView.setImageUrl(fileName);
        gameViewMapper.insert(gameView);
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            // 1. 先删除数据库
            GameView gameView = gameViewMapper.getById(id);
            gameViewMapper.deleteById(id);
            // 2. 再删除磁盘中的文件
            if (gameView.getImageUrl() != null && !gameView.getImageUrl().isEmpty()) {
                IOUtil.deleteFileOrDirectory(basePath +
                        "/" + gameView.getGameId() +
                        "/" + FileNameConstant.GAME_FOLDER_NAME +
                        "/" + gameView.getImageUrl());
            } else if (gameView.getVideoUrl() != null && !gameView.getVideoUrl().isEmpty()) {
                IOUtil.deleteFileOrDirectory(basePath +
                        "/" + gameView.getGameId() +
                        "/" + FileNameConstant.GAME_FOLDER_NAME +
                        "/" + gameView.getVideoUrl());
            }

        }
    }
}
